<template>
    <div ref="scrubber" class="scrubber-box" @mousedown="scrubbing = true">
        <div class="relative">
            <div class="cache" :style="{ transform: `translateX(${secondary / max * 100 - 100}%)` }"/>
            <div class="progress" :style="{ transform: `translateX(${value / max * 100 - 100}%)` }"/>
        </div>
        <div class="time-progress" :class="{ sub: scrubbing }">
            <slot :pending-value="pendingValue"
                  :position="`${Math.max(0, Math.min(<number>elementX, <number>elementWidth))-10}px`"/>
        </div>
    </div>
</template>

<script setup lang="ts">
import {ref, watch} from 'vue-demi'
import {useEventListener, useMouseInElement, useVModel} from '@vueuse/core'

const props = defineProps({
    min: {type: Number, default: 0},
    max: {type: Number, default: 100},
    secondary: {type: Number, default: 0},
    modelValue: {type: Number, required: true},
})

const emit = defineEmits(['update:modelValue'])

const scrubber = ref()
const scrubbing = ref(false)
const pendingValue = ref(0)

useEventListener('mouseup', () => scrubbing.value = false)

const value = useVModel(props, 'modelValue', emit)
const {elementX, elementWidth} = useMouseInElement(scrubber)

watch([scrubbing, elementX], () => {
    const progress = Math.max(0, Math.min(1, (elementX.value) / elementWidth.value))
    pendingValue.value = progress * props.max
    if (scrubbing.value)
        value.value = pendingValue.value
})
</script>

<style scoped lang="scss">
.scrubber-box {
  position: relative;
  width: 100%;
  height: 100%;

  .relative {
    position: relative;
    width: 100%;
    height: 100%;

    .cache {
      position: absolute;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(73, 70, 70, 0.6);
      border-radius: 0.1rem;
    }

    .progress {
      position: absolute;
      top: 0;
      width: 100%;
      height: 100%;
      background: var(--main-1-h8);
      border-radius: 0.1rem;

      &:after {
        position: absolute;
        top: 0;
        right: -0.05rem;
        content: '';
        width: 0.2rem;
        height: 0.15rem;
        background: var(--main-1-h2);
        border-radius: 0.05rem;
        cursor: url(@/assets/cursor/link.cur), auto;
      }

      &:hover:after {
        background: #FF8066;
        box-shadow: 0 0 0.04rem 0.02rem var(--box-shadow-c);
      }
    }
  }

  .time-progress {
    opacity: 0;
  }

  .time-progress.sub {
    opacity: 1;
  }
}

</style>